<?php

namespace App\Models;

use App\Models\Device;
use App\Models\DeviceGroup;
use App\Models\Task;
use Illuminate\Database\Eloquent\Model;

class DeviceGroupTask extends Model
{
  protected $fillable = [
    'device_group_id',
    'publish_start_time',
    'publish_end_time',
    'task_id',
    'priority',
  ];

  public function task()
  {
    return $this->belongsTo(Task::class);
  }

  public function deviceGroup()
  {
    return $this->belongsTo(DeviceGroup::class);
  }

  public function finishedDevices()// 只返回当天完成任务的设备
  {
    return $this->belongsToMany(Device::class,'task_device', 'device_group_task_id', 'device_id')
        ->where(\DB::raw("DATE_FORMAT(finished_time,'%Y-%m-%d')"), '=', \Carbon\Carbon::now()->toDateString());
  }

  public function deviceIsFinished($device_id)
  {
    return $this->finishedDevices->contains($device_id);
  }

  public function addFinishedDevices($device_ids)
  {
    if(!is_array($device_ids)) {
      $device_ids = compact('device_ids');
    }
    $this->finishedDevices()->attach($device_ids);
  }
}
